from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .models import FeedingSchedule, FeedingLog
from pets.models import Pet
from .serializers import FeedingScheduleSerializer, FeedingLogSerializer
from django.utils import timezone
from datetime import datetime


class FeedingScheduleAPI(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pet_id):
        pet = get_object_or_404(Pet, id=pet_id, owner=request.user)
        schedules = FeedingSchedule.objects.filter(pet=pet, is_active=True)
        serializer = FeedingScheduleSerializer(schedules, many=True)
        return Response(serializer.data)

    def post(self, request, pet_id):
        pet = get_object_or_404(Pet, id=pet_id, owner=request.user)
        serializer = FeedingScheduleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(pet=pet)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class FeedingLogAPI(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = FeedingLogSerializer(data=request.data)
        if serializer.is_valid():
            pet_id = serializer.validated_data['pet_id']
            pet = get_object_or_404(Pet, id=pet_id, owner=request.user)

            # 自动关联最近的喂食计划
            schedule = FeedingSchedule.objects.filter(
                pet=pet,
                is_active=True,
                food_type=serializer.validated_data.get('food_type')
            ).first()

            log = serializer.save(pet=pet, schedule=schedule)
            return Response(FeedingLogSerializer(log).data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class NextFeedingAPI(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pet_id):
        pet = get_object_or_404(Pet, id=pet_id, owner=request.user)
        schedules = FeedingSchedule.objects.filter(pet=pet, is_active=True)

        next_feeding = None
        for schedule in schedules:
            next_time = schedule.next_feeding_time()
            if not next_feeding or next_time < next_feeding['time']:
                next_feeding = {
                    'time': next_time,
                    'schedule_id': schedule.id,
                    'food_type': schedule.food_type.name if schedule.food_type else None,
                    'amount': schedule.amount
                }

        if next_feeding:
            return Response({
                'next_feeding': next_feeding['time'].isoformat(),
                'food_type': next_feeding['food_type'],
                'amount': next_feeding['amount'],
                'schedule_id': next_feeding['schedule_id']
            })
        return Response({'message': 'No active feeding schedules'}, status=status.HTTP_404_NOT_FOUND)